package cn.edu.tju.elm.service;

import cn.edu.tju.core.model.User;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.elm.model.DeliveryAddress;
import cn.edu.tju.elm.repository.DeliveryAddressRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class AddressService {

    @Autowired
    private DeliveryAddressRepository deliveryAddressRepository;
    
    @Autowired
    private UserService userService;

    /**
     * 添加配送地址
     * @param deliveryAddress 配送地址信息
     * @return 保存后的配送地址
     */
    public DeliveryAddress addDeliveryAddress(DeliveryAddress deliveryAddress) {
        // 验证必要字段
        if (deliveryAddress.getContactName() == null || deliveryAddress.getContactName().trim().isEmpty()) {
            throw new IllegalArgumentException("联系人姓名不能为空");
        }
        if (deliveryAddress.getContactTel() == null || deliveryAddress.getContactTel().trim().isEmpty()) {
            throw new IllegalArgumentException("联系电话不能为空");
        }
        if (deliveryAddress.getAddress() == null || deliveryAddress.getAddress().trim().isEmpty()) {
            throw new IllegalArgumentException("配送地址不能为空");
        }
        
        // 自动填充customer信息
        if (deliveryAddress.getCustomer() == null) {
            // 从当前认证用户获取customer信息
            User currentUser = userService.getUserWithAuthorities().orElse(null);
            if (currentUser != null) {
                deliveryAddress.setCustomer(currentUser);
            } else {
                throw new IllegalArgumentException("用户未认证或不存在");
            }
        }
        return deliveryAddressRepository.save(deliveryAddress);
    }

    /**
     * 根据ID获取配送地址
     * @param id 配送地址ID
     * @return 配送地址信息
     */
    public Optional<DeliveryAddress> getDeliveryAddressById(Long id) {
        return deliveryAddressRepository.findById(id);
    }

    /**
     * 获取用户的所有配送地址
     * @param userId 用户ID
     * @return 配送地址列表
     */
    public List<DeliveryAddress> getDeliveryAddressesByUserId(Long userId) {
        return deliveryAddressRepository.findAll().stream()
                .filter(address -> address.getCustomer() != null && address.getCustomer().getId().equals(userId))
                .collect(Collectors.toList());
    }

    /**
     * 更新配送地址
     * @param id 配送地址ID
     * @param deliveryAddress 新的配送地址信息
     * @return 更新后的配送地址
     */
    public DeliveryAddress updateDeliveryAddress(Long id, DeliveryAddress deliveryAddress) {
        Optional<DeliveryAddress> addressOpt = deliveryAddressRepository.findById(id);
        if (addressOpt.isPresent()) {
            DeliveryAddress existingAddress = addressOpt.get();
            existingAddress.setContactName(deliveryAddress.getContactName());
            existingAddress.setContactSex(deliveryAddress.getContactSex());
            existingAddress.setContactTel(deliveryAddress.getContactTel());
            existingAddress.setAddress(deliveryAddress.getAddress());
            return deliveryAddressRepository.save(existingAddress);
        }
        return null;
    }

    /**
     * 删除配送地址
     * @param id 配送地址ID
     * @return 是否删除成功
     */
    public boolean deleteDeliveryAddress(Long id) {
        if (deliveryAddressRepository.existsById(id)) {
            deliveryAddressRepository.deleteById(id);
            return true;
        }
        return false;
    }
}